package com.example.usbcamerademo;

import android.annotation.SuppressLint;
import android.graphics.SurfaceTexture;
import android.hardware.usb.UsbDevice;
import android.os.Bundle;
import android.view.Surface;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.serenegiant.usb.CameraDialog;
import com.serenegiant.usb.USBMonitor;
import com.serenegiant.usbcameracommon.UVCCameraHandler;
import com.serenegiant.widget.CameraViewInterface;
//Java实现
public class MainActivityJava extends AppCompatActivity implements CameraDialog.CameraDialogParent {

    private static final boolean USE_SURFACE_ENCODER = false;
    private static final int PREVIEW_WIDTH = 320;
    private static final int PREVIEW_HEIGHT = 240;
    private static final int PREVIEW_MODE = 1; // YUV

    // 第一个摄像头相关
    private UVCCameraHandler mCameraHandler1;
    private CameraViewInterface mUVCCameraView1;
    private ImageButton mCameraButton1;

    // 第二个摄像头相关
    private UVCCameraHandler mCameraHandler2;
    private CameraViewInterface mUVCCameraView2;
    private ImageButton mCameraButton2;

    private USBMonitor mUSBMonitor;
    private int currentCamera; // 标记当前操作的摄像头 (1 or 2)

    @Override
    @SuppressLint("MissingInflatedId")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);

        // 初始化第一个摄像头控件
        mCameraButton1 = findViewById(R.id.btn_camera1);
        mCameraButton1.setOnClickListener(v -> openCamera(1));
        final View view1 = findViewById(R.id.camera_view1);
        mUVCCameraView1 = (CameraViewInterface) view1;
        mUVCCameraView1.setAspectRatio(PREVIEW_WIDTH / (double) PREVIEW_HEIGHT);

        // 初始化第二个摄像头控件
        mCameraButton2 = findViewById(R.id.btn_camera2);
        mCameraButton2.setOnClickListener(v -> openCamera(2));
        final View view2 = findViewById(R.id.camera_view2);
        mUVCCameraView2 = (CameraViewInterface) view2;
        mUVCCameraView2.setAspectRatio(PREVIEW_WIDTH / (double) PREVIEW_HEIGHT);

        mUSBMonitor = new USBMonitor(this, mOnDeviceConnectListener);

        // 创建两个摄像头处理器
        mCameraHandler1 = UVCCameraHandler.createHandler(this, mUVCCameraView1,
                USE_SURFACE_ENCODER ? 0 : 1, PREVIEW_WIDTH, PREVIEW_HEIGHT, PREVIEW_MODE);
        mCameraHandler2 = UVCCameraHandler.createHandler(this, mUVCCameraView2,
                USE_SURFACE_ENCODER ? 0 : 1, PREVIEW_WIDTH, PREVIEW_HEIGHT, PREVIEW_MODE);

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
    }

    private void openCamera(int cameraIndex) {
        currentCamera = cameraIndex; // 设置当前要操作的摄像头
        CameraDialog.showDialog(MainActivityJava.this);
    }

    private final USBMonitor.OnDeviceConnectListener mOnDeviceConnectListener = new USBMonitor.OnDeviceConnectListener() {
        @Override
        public void onAttach(final UsbDevice device) {
            Toast.makeText(MainActivityJava.this, "USB_DEVICE_ATTACHED", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onConnect(final UsbDevice device, final USBMonitor.UsbControlBlock ctrlBlock, final boolean createNew) {
            // 根据当前选择的摄像头连接到对应的处理器
            switch (currentCamera) {
                case 1:
                    if (mCameraHandler1 != null) {
                        // 如果第一个摄像头已经打开，先关闭
                        if (mCameraHandler1.isOpened()) {
                            mCameraHandler1.close();
                        }
                        mCameraHandler1.open(ctrlBlock);
                        startPreview(1);
                    }
                    break;
                case 2:
                    if (mCameraHandler2 != null) {
                        // 如果第二个摄像头已经打开，先关闭
                        if (mCameraHandler2.isOpened()) {
                            mCameraHandler2.close();
                        }
                        mCameraHandler2.open(ctrlBlock);
                        startPreview(2);
                    }
                    break;
                default:
                    // 默认连接到第一个摄像头
                    if (mCameraHandler1 != null) {
                        if (mCameraHandler1.isOpened()) {
                            mCameraHandler1.close();
                        }
                        mCameraHandler1.open(ctrlBlock);
                        startPreview(1);
                    }
                    break;
            }
        }

        @Override
        public void onDisconnect(final UsbDevice device, final USBMonitor.UsbControlBlock ctrlBlock) {
            // 停止对应摄像头的预览
        }

        @Override
        public void onDettach(final UsbDevice device) {
            Toast.makeText(MainActivityJava.this, "USB_DEVICE_DETACHED", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(final UsbDevice device) {
        }
    };

    private void startPreview(int cameraIndex) {
        switch (cameraIndex) {
            case 1:
                if (mCameraHandler1 != null) {
                    final SurfaceTexture st = mUVCCameraView1.getSurfaceTexture();
                    // 确保之前的预览已经停止
                    mCameraHandler1.stopPreview();
                    mCameraHandler1.startPreview(new Surface(st));
                }
                break;
            case 2:
                if (mCameraHandler2 != null) {
                    final SurfaceTexture st = mUVCCameraView2.getSurfaceTexture();
                    // 确保之前的预览已经停止
                    mCameraHandler2.stopPreview();
                    mCameraHandler2.startPreview(new Surface(st));
                }
                break;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        mUSBMonitor.register();
    }

    @Override
    protected void onStop() {
        mUSBMonitor.unregister();
        super.onStop();
    }

    @Override
    public void onDestroy() {
        if (mUSBMonitor != null) {
            mUSBMonitor.destroy();
            mUSBMonitor = null;
        }
        if (mCameraHandler1 != null) {
            mCameraHandler1.release();
            mCameraHandler1 = null;
        }
        if (mCameraHandler2 != null) {
            mCameraHandler2.release();
            mCameraHandler2 = null;
        }
        super.onDestroy();
    }

    @Override
    public USBMonitor getUSBMonitor() {
        return mUSBMonitor;
    }

    @Override
    public void onDialogResult(boolean b) {
    }
}
